package com.baike.shiro;

import com.baike.entity.TbTeacher;
import com.baike.service.ITbTeacherService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author:pjm
 * 自定义的realm类,需要继承AuthenticctingRealm:只有登录功能;AuthorizingRealm:有登录和授权功能
 */
public class LoginRelam extends AuthorizingRealm {
    @Autowired
    private ITbTeacherService teacherService;
    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权方法");
        //授权方法
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return null;
    }
    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1. 获取token对象
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //查询账号对应的对象
        TbTeacher teacher = teacherService.selectByUserName(token.getUsername());
        if (teacher == null){
            //账号不存在
           return null;
        }
        String teacherName = teacher.getTeacherName();
        System.out.println("用户为"+ teacherName);

        //System.out.println("验证通过" + teacherName);
        //3. 验证密码(shiro加密)  第一个参数为 成功后需要放到session中的对象 第二个 数据库中用户的密码 第三个 加密的盐  第四个:用户的名字(账号)
        return new SimpleAuthenticationInfo(teacher,teacher.getTeacherPassword(), ByteSource.Util.bytes(teacher.getSalt()),teacher.getTeacherName());
    }
}
